/*
 *  clusters.cpp
 *  bgsubtraction
 *
 *  Created by a1gucis on 4/5/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

#include "clusters.h"

Clusters::Clusters() {
	this->clusters = new vector<Cluster *>();
}

Clusters::~Clusters() {
	this->clusters->clear();
	delete this->clusters;
}

void Clusters::addLabel(int label) {
	sorted = false;
	bool found = false;
	for (int i=0;i<clusters->size();i++) {
		Cluster *clust = (*clusters)[i]; 
		if (clust->label == label) {
			clust->quantity++;
			found = true;
		}
	}
	if (!found) {
		Cluster *clust = new Cluster();
		clust->label = label;
		clust->quantity = 1;
		this->clusters->push_back(clust);
	}
}

int Clusters::getMaxLabel() {
	/*int maxLabel = (*clusters)[0].label;
	int maxQuantity = (*clusters)[0].quantity;
	for (int i=0;i<clusters->size();i++) {
		Cluster clust = (*clusters)[i];
		if (clust.quantity > maxQuantity) {
			maxLabel = clust.label;
			maxQuantity = clust.quantity;
		}
	}*/
	
	//return maxLabel;
	int maxLabel = getLabel(1);
	return maxLabel;
}

int Clusters::getLabel(int pos) {
	if (pos > clusters->size()) {
		//cout<<"ERROR!!!Clusters::getLabel(int pos) pos > clusters size"<<endl;
		return -1;
	}
	if (!sorted)
		sort();
	Cluster *clust = (*clusters)[pos-1];
	return clust->label;
}

void Clusters::clear() {
	clusters->clear();
}

void Clusters::sort() {
	sorted = true;
	Cluster *maxClust, *tmpClust;
	int maxPos;
	for (int i=0;i<clusters->size()-1;i++) {
		maxClust = (*clusters)[i];
		maxPos = i;
		for (int j=i+1;j<clusters->size();j++) {
			tmpClust = (*clusters)[j];
			if (tmpClust->quantity > maxClust->quantity) {
				maxClust = tmpClust;
				maxPos = j;
			}
		}
		tmpClust = (*clusters)[i];
		maxClust = (*clusters)[maxPos];
		(*clusters)[i] = maxClust;
		(*clusters)[maxPos] = tmpClust;
	}
}

//debug purposes
void Clusters::print() {
	cout<<"Size: "<<clusters->size()<<endl;
	for (int i=0;i<clusters->size();i++) {
		Cluster *clust = (*clusters)[i];
		cout<<"Cluster: "<<clust->label<<", quantity: "<<clust->quantity<<endl;
	}
}

int Clusters::getSize() {
	return clusters->size();
}